package com.veetao.api.filter;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.veetao.api.consts.HttpConstants;
import com.veetao.api.model.ApiResult;
import com.veetao.api.model.ApiResultCode;
import com.veetao.api.service.CommandLookupService;
import com.veetao.api.service.MobileClientAppService;
import com.veetao.api.service.PassportService;
import com.veetao.api.utils.McpUtils;
import com.veetao.api.utils.NumberUtil;
import com.veetao.api.utils.RequestUtils;

@Component
public class AuthorizationChecker extends ApiRequestChecker {


	@Autowired
	private CommandLookupService commandLookupService;
	@Autowired
	private PassportService passportService;
	@Autowired
	private MobileClientAppService mobileClientAppService;

	public AuthorizationChecker() {
		super();
		this.setOrder(3);
	}

	@Override
	public ApiResult check(HttpServletRequest request) {
		int appId = NumberUtils.toInt(RequestUtils.get(request, HttpConstants.PARAM_APP_ID));
		
		
		String clientIp = request.getRemoteAddr();
		String methodName = McpUtils.getCmdMethodFromURI(request.getRequestURI());
		if (!mobileClientAppService.isAllowedApiMethod(appId, methodName, clientIp)) {
			return new ApiResult(ApiResultCode.E_SYS_PERMISSION_DENY);
		}
		
		String version = RequestUtils.get(request, HttpConstants.PARAM_VER);
		if(!this.commandLookupService.isNeedLogin(methodName, version)) {
			return SUCC_RESULT;
		}
		
		String ticket = RequestUtils.get(request, HttpConstants.PARAM_TICKET);
		if(ticket == null) {
			return new ApiResult(ApiResultCode.E_SYS_INVALID_TICKET);
		}
		
		String userIdStr = RequestUtils.get(request, HttpConstants.PARAM_UID);
		if(userIdStr == null || ! NumberUtil.isNumber(userIdStr)) {
			return new ApiResult(ApiResultCode.E_SYS_INVALID_TICKET);
		}
		int userId = Integer.valueOf(userIdStr);
		if (userId == 0 || !passportService.checkTicket(userId, ticket)) {
			return new ApiResult(ApiResultCode.E_SYS_INVALID_TICKET);
		}
		
		return SUCC_RESULT;
	}

}
